<script lang="ts" setup>

// 接收页面参数
import {getAnimalsListBySearchApi} from "@/api/ainmalsList";
import {onLoad, onPullDownRefresh} from "@dcloudio/uni-app";
import {computed, ref} from "vue";
import type {AnimalSearchResult, AnimalsListItem} from "@/types/animals";
import type {ImgError} from "@/types/error";
import {ImgErrorType} from "@/enum/imgErrorType";
import {useCategoryStore} from "@/stores/category";
import type {SwiperOnChange} from "@uni-helper/uni-app-types";
import {AnimalSortType} from "@/enum/animalSortType";

const {safeAreaInsets, windowWidth} = uni.getSystemInfoSync() // 顶部安全距离
/**
 * 下拉刷新
 */
onPullDownRefresh(() => {
  switch (activeIndex.value) {
    case AnimalSortType.All:
      animalsList.value = []
      break;
    case AnimalSortType.HOT:
      animalsListHot.value = []
      break;
    case AnimalSortType.SCORE:
      animalsListScore.value = []
      break;
  }

  getAnimalsList(activeIndex.value)
  uni.stopPullDownRefresh()
})


// 接收页面参数
const pageQuery = defineProps<{
  keyword?: string
  categoryId?: string
}>()

// nav
const navList = [
  {
    value: 0,
    text: '全部'
  },
  {
    value: 1,
    text: '图文'
  },
  {
    value: 2,
    text: '图集'
  }
]
const animalsList = ref<AnimalsListItem[]>([]) // 默认列表数据
const animalsListHot = ref<AnimalsListItem[]>([]) // 默认列表数据
const animalsListScore = ref<AnimalsListItem[]>([]) // 默认列表数据
const page = ref<number[]>(new Array(navList.length).fill(1)) // 页码
// const type = ref<number>(0) // 0 全部 ，1 热度，2 评分
const categoryStore = useCategoryStore()
const activeCategory = ref<string>('') // 当前激活分类
activeCategory.value = pageQuery.categoryId || ''
const oldActiveCategory = ref<string>('') // 当前分类
// 获取分类列表
const categoryList = computed(() => {
  return categoryStore.categoryList.map((item) => {
    return {
      value: item.id.toString(),
      text: item.name
    }
  })
})
/**
 * 初始化数据
 */
const getAnimalsList = async (type: AnimalSortType) => {
  uni.showLoading({title: '加载中...'})
  let pageNum: number
  switch (type) {
    case AnimalSortType.All:
      pageNum = page.value[0];
      break;
    case AnimalSortType.HOT:
      pageNum = page.value[1];
      break;
    case AnimalSortType.SCORE:
      pageNum = page.value[2];
      break;
  }
  const res = await getAnimalsListBySearchApi(pageQuery.keyword!, {
    page: pageNum,
    pageSize: 20,
    categoryId: activeCategory.value || '',
    type: type
  })
  res.data.data.forEach((item: AnimalSearchResult) => {
    item.name = item.name.replace(new RegExp(pageQuery.keyword!, 'g'), `<em style="color: #39c5bb;font-style: normal;">${pageQuery.keyword}</em>`)
    if (item.tags && item.tags.length > 0)
    item.tags= item.tags.replace(new RegExp(pageQuery.keyword!, 'g'), `<em style="color: #39c5bb;font-style: normal;">${pageQuery.keyword}</em>`)
  })
  if (res.data.page * res.data.pageSize >= res.data.total) { // 返回的数据长度小于分页数
    isNoMore.value[activeIndex.value] = true
  }
  uni.hideLoading()
  if (type === AnimalSortType.HOT) {
    // 按照热度排序
    if (animalsListHot.value?.length > 0) {
      return animalsListHot.value = [...animalsListHot.value, ...res.data.data]
    }
    return animalsListHot.value = res.data.data
  } else if (type === AnimalSortType.SCORE) {
    // 按照评分排序
    if (animalsListScore.value?.length > 0) {
      return animalsListScore.value = [...animalsListScore.value, ...res.data.data]
    }
    return animalsListScore.value = res.data.data
  }
  if (animalsList.value?.length > 0) {
    // animalsList.value=[...animalsList.value,...res.data.data]
    return animalsList.value = animalsList.value.concat(res.data.data)
  }
  animalsList.value = res.data.data
}

// 选中的nav索引，默认0（全部）
const activeIndex = ref<number>(0)
const slideLeft = ref(80)
const swiperHeight = computed(() => {
  switch (activeIndex.value) {
    case AnimalSortType.All:
      return (Math.floor(animalsList.value.length / 2) + 1) * 520 + 80
    case AnimalSortType.HOT:
      return (Math.floor(animalsListHot.value.length / 2) + 1) * 520 + 80
    case AnimalSortType.SCORE:
      return (Math.floor(animalsListScore.value.length / 2) + 1) * 520 + 80
  }
})
/**
 * the thing of clickNav
 * @param index 点击索引
 */
const onClickNav = (index: number) => {
  activeIndex.value = index
}
const isSwiperChange = ref(false)
/**
 * When the swiper change
 * @param e 轮播图切换时返回对象
 */
const onSwiperChange: SwiperOnChange = (e) => {
  isSwiperChange.value = true
  activeIndex.value = e.detail.current
  // 切换后重新发起请求，开启过滤
  //只有当该列表之前没有被加载狗才去发送请求(因为默认页是一定会展示的所以就不用判断)
  if (activeIndex.value === AnimalSortType.HOT && animalsListHot.value.length < 1) {
    getAnimalsList(activeIndex.value)
  } else if (activeIndex.value === AnimalSortType.SCORE && animalsListScore.value.length < 1) {
    getAnimalsList(activeIndex.value)
  } else if (activeIndex.value === AnimalSortType.All && animalsList.value.length < 1) {
    getAnimalsList(activeIndex.value)
  }
  setTimeout(() => {
    isSwiperChange.value = false
  }, 200)

}

/**
 * 图片加载失败
 * @param errorImg 图片错误内容
 */
const onImgError = (errorImg: ImgError) => {
  switch (errorImg.secondaryType) {
    case AnimalSortType.All:
      animalsList.value![errorImg.index].img = ImgErrorType.ERROR_IMG_URL
      break
    case AnimalSortType.HOT:
      animalsListHot.value![errorImg.index].img = ImgErrorType.ERROR_IMG_URL
      break
    case AnimalSortType.SCORE:
      animalsListScore.value![errorImg.index].img = ImgErrorType.ERROR_IMG_URL
      break
    default:
      break
  }
}
/**
 * 返回
 */
const goBack = () => uni.navigateBack()

onLoad(() => {
  getAnimalsList(activeIndex.value)
})

//点击搜索框
const goSearch = (type: 0 | 1) => {
  console.log(type)
  if (type === 0) {
    uni.$emit('goSearch',pageQuery.keyword)
    return uni.navigateBack()
  }
  uni.navigateBack()
}
const drawer = ref()
// 打开抽屉
const onShowDrawer = () => {
  drawer.value.open()
  oldActiveCategory.value = activeCategory.value
}

// 点击分类
/**
 * change the active category
 * @param id active category id
 */
const onChooseCategory = (id: string) => {
  activeCategory.value = id
}

/**
 * Triggered after confirming the category selection
 */
const onConfirmCategory = () => {
  drawer.value.close()
  if (activeCategory.value === oldActiveCategory.value) {
    // 分类数据并没有修改
    return
  }
  animalsList.value = []
  animalsListHot.value = []
  animalsListScore.value = []
  // 重新加载数据
  getAnimalsList(activeIndex.value)
}
/**
 * 触底加载
 */
const isNoMore = ref<boolean[]>(new Array(3).fill(false))// 判断是否还有数据
const isLoadMore = ref(false) //节流阀

const onScrollLower = () => {
  if (isLoadMore.value) {
    return
  }
  if (isNoMore.value[activeIndex.value]) {
    return uni.showToast({title: '没有更多数据了', icon: 'none'})
  }
  isLoadMore.value = true
  // change the page
  switch (activeIndex.value) {
    case AnimalSortType.All:
      page.value[0]++;
      break;
    case AnimalSortType.HOT:
      page.value[1]++;
      break;
    case AnimalSortType.SCORE:
      page.value[2]++;
      break;
  }
  getAnimalsList(activeIndex.value)
  isLoadMore.value = false
}
// 手指滑动
const onTouchMove: UniHelper.SwiperOnTransition = (event) => {
}


// 回到顶部
const scrollTop = ref([0, 0, 0])
const scrollView = ref()
const backTop = ref([-1, -1, -1])
const onScrollList = (e: UniHelper.ScrollViewOnScrollEvent) => {
  scrollTop.value[activeIndex.value] = e.detail.scrollTop
}
const scrollToTop = () => {
  backTop.value[activeIndex.value] = 0
  console.log(backTop.value[activeIndex.value])
}
const initBackTop = () => {
  backTop.value[activeIndex.value] = -1
}
const backTopStyle = {
  backgroundColor: 'rgba(57,197,187,0.75)',
}
const iconStyle = {
  color: '#fff',
  fontSize: '24px',
}
</script>
<template>
  <view style="height: 100vh">
    <!--    返回顶部-->
    <uv-back-top :custom-style="backTopStyle" :icon-style="iconStyle" :scroll-top="scrollTop[activeIndex]"
                 @click="scrollToTop"></uv-back-top>
    <!--  顶部搜索栏  -->
    <view :style="{ paddingTop: safeAreaInsets?.top! + 20 + 'px', fontSize: '16px', paddingLeft: '20rpx' }"
          class="navbar cuIcon-back text-white">
      <view class="" style="width: 30px;height: 30px;position: absolute;left: 30rpx" @click="goBack"></view>
      <view class="text-white text-df round cuIcon-search padding-left-sm text-lg" style="flex-grow: 1;margin-left: 20rpx;width: 100%;position: relative;
          display: flex;
          align-items: center;
          justify-content: flex-start;
          height:80rpx; background-color: rgba(255,255,255,0.3);font-size: 40rpx" @tap="goSearch(0)">
        <text class="text-df margin-left-sm">{{ pageQuery.keyword ? pageQuery.keyword : '搜索动物朋友' }}</text>
        <view style="position: absolute;top: 50%;transform: translateY(-50%);right: 5%" @tap.stop="goSearch(1)">
          <text class="cuIcon-roundclosefill" style="font-size: 38rpx;color: #f1f1f1;">
          </text>
        </view>
      </view>

      <view class="cuIcon-cascades margin-lr-sm" style="font-size: 46rpx;justify-self: flex-end" @click="onShowDrawer">
      </view>
    </view>
    <!--   分类 -->
    <view class="cu-bar solid-bottom category-nav  bg-white flex-row justify-between" style="padding: 0 10%">
      <view v-for="(item, index) in navList" :key="index" :class="{ 'active-nav': activeIndex === index }"
            @click="onClickNav(index)">{{ item.text }}
      </view>
      <view :class="{ 'left': activeIndex === 0, 'center': activeIndex === 1, 'right': activeIndex === 2 }"
            :style="{ width: isSwiperChange ? '5rem' : '2rem' }" class="slide bg-gradual-awGreen round"></view>
    </view>

    <!--    切换区域-->
    <swiper :current="activeIndex" class="swiper-container" style="height: 90vh" @change="onSwiperChange"
            @transition="onTouchMove">
      <swiper-item class="swiper-a" style="height: 100%">
        <view v-if="animalsList?.length < 1" class="flex justify-center align-center flex-column"
              style="width: 100%;height: 70vh">
          <uv-empty icon-size="120" mode="search" text="没有搜索到相关动物哟~（＞人＜；）"></uv-empty>
        </view>
        <scroll-view v-else ref="scrollView" :scroll-top="backTop[0]"
                     :scroll-y="true"
                     scroll-with-animation="true"
                     style="height: 100%"
                     upper-threshold="0"
                     @scroll="onScrollList"
                     @scrolltolower="onScrollLower"
                     @scrolltoupper="initBackTop">
          <aw-animals-list :animals-list="animalsList" :show-page-view="true"
                           :show-name="true" :type="AnimalSortType.All"
                           @imgError="onImgError"></aw-animals-list>
          <text v-if="isNoMore[AnimalSortType.All]">没有更多了哟~(≧∇≦)ﾉ</text>
          <aw-loader v-else></aw-loader>
        </scroll-view>
      </swiper-item>

      <swiper-item class="swiper-a" style="height: 100%">
        <view v-if="animalsListHot?.length < 1" class="flex justify-center align-center flex-column"
              style="width: 100%;height: 70vh">
          <!--          <image mode="aspectFit" src="/static/collect-empty.png" style="width: 250rpx;height: 250rpx"></image>-->
          <!--          <view class="text-gray text-lg">没有搜索到相关动物哟~（＞人＜；）</view>-->
          <uv-empty icon-size="120" mode="search" text="没有搜索到相关动物哟~（＞人＜；）"></uv-empty>
        </view>
        <scroll-view v-else ref="scrollView" :scroll-top="backTop[1]" :scroll-y="true"
                     scroll-with-animation="true"
                     style="height: 100%"
                     upper-threshold="0"
                     @scroll="onScrollList"
                     @scrolltolower="onScrollLower"
                     @scrolltoupper="initBackTop">
          <aw-animals-list :animals-list="animalsListHot" :show-name="true"
                           :show-page-view="true"
                           :type="AnimalSortType.HOT"
                           @imgError="onImgError"></aw-animals-list>
          <text v-if="isNoMore[AnimalSortType.HOT]">没有更多了哟~(≧∇≦)ﾉ</text>
          <aw-loader v-else></aw-loader>
        </scroll-view>
      </swiper-item>

      <swiper-item class="swiper-a" style="height: 100%">
        <view v-if="animalsListScore?.length < 1" class="flex justify-center align-center flex-column"
              style="width: 100%;height: 70vh">
          <!--          <image mode="aspectFit" src="/static/collect-empty.png" style="width: 250rpx;height: 250rpx"></image>-->
          <!--          <view class="text-gray text-lg">没有搜索到相关动物哟~（＞人＜；）</view>-->
          <uv-empty icon-size="120" mode="search" text="没有搜索到相关动物哟~（＞人＜；）"></uv-empty>
        </view>
        <scroll-view v-else ref="scrollView" :scroll-top="backTop[2]" :scroll-y="true"
                     scroll-with-animation="true"
                     style="height: 100%"
                     upper-threshold="0"
                     @scroll="onScrollList"
                     @scrolltolower="onScrollLower"
                     @scrolltoupper="initBackTop">
          <aw-animals-list :animals-list="animalsListScore" :show-page-view="true"
                           :show-name="true" :type="AnimalSortType.SCORE"
                           @imgError="onImgError"></aw-animals-list>
          <text v-if="isNoMore[AnimalSortType.SCORE]">没有更多了哟~(≧∇≦)ﾉ</text>
          <aw-loader v-else></aw-loader>
        </scroll-view>
      </swiper-item>
    </swiper>

    <!--   侧边抽屉 -->
    <uni-drawer ref="drawer" :mask-click="false" :width="120" mode="right">
      <view class="flex-column flex justify-start align-center" style="padding-top: 180rpx">
        <view class="title text-lg text-grey margin-bottom-sm"
              style="font-weight: bold;border-bottom: #39c5bb 1rpx solid">选择分类
        </view>
        <view :class="{ 'active-category': activeCategory === '' }" class="margin-top-lg text-gray category"
              @click="onChooseCategory('')">全部
        </view>
        <view v-for="(item, index) in categoryList" :key="item.value"
              :class="{ 'active-category': activeCategory === item.value }" class="margin-top-xl text-gray category"
              @click="onChooseCategory(item.value)">
          {{ item.text }}
        </view>
        <view class="cu-btn text-white round bg-gradual-awGreen margin-top-xl" style="width: 80%"
              @click="onConfirmCategory">确定
        </view>
      </view>
    </uni-drawer>
  </view>

</template>


<style lang="scss" scoped>
/* #ifdef H5 */
body {
  background-color: #f1f1f1;
}

/* #endif */
.navbar {
  width: 100%;
  height: 200rpx;
  /* #ifdef H5 */
  height: 180rpx;
  /* #endif */
  display: flex;
  align-items: center;
  justify-content: flex-start;
  background-color: #39c5bb;
  padding-bottom: 10px;
  // 固定
  z-index: 999;
  background-image: url('@/static/circle.png');
  background-size: 80% 200%;
  background-repeat: repeat-x;
  position: fixed;
  top: 0;
  // 右上角
  background-origin: border-box;
  // 背景图片位置
  background-position: left -10px bottom 50px;

  .nav-title {
    position: absolute;
    color: #f1f1f1;
    left: 10px;
    top: 30%;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 20px;
    font-family: 'Helvetica Neue', Helvetica;

    .text {
      padding-left: 10px;
      border-left: #f1f1f1 1px solid;
      margin-left: 20px;
      font-size: 16px;
      display: flex;
      align-items: center;
    }
  }

  .nav-item {
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 0 5px;

    image {
      width: 35px;
      height: 35px;
      margin-right: 10px;
    }

    input {
      border: #3ebed3 1px solid;
      border-radius: 20px;
      background-color: rgba(255, 255, 255, 0.3);
      height: 40px;
      padding-left: 40px;
      color: rgba(255, 255, 255, 0.83);
      background-image: url('@/static/search.png');
      background-repeat: no-repeat;
      background-position: 10px center;
      background-size: 20px;

      &::placeholder {
        color: #fff;
      }
    }
  }

  .img {
    border-radius: 50%;
    border: #3ebed3 1px solid;
    background-color: #3ebed3;
    width: 28px;
    height: 28px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}

.swiper-container {
  margin-top: 5px;
  width: 100%;
  height: 100%;
}

.swiper-a {
  height: 100%;
  width: 100%;

  text {
    width: 100%;
    margin-bottom: 20rpx;
    font-size: 30rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #aaaaaa;
  }
}

.category-nav {
  transition: all 0.5s ease-in-out;
  width: 100%;
  height: 100rpx;
  margin-top: 190rpx;
  background: rgba(241, 241, 241, 0.7);
  position: relative;
  border-bottom: #dbdbdb 2px solid;

  view {
    font-size: 16px;
    color: #333333;
  }

  .active-nav {
    color: #39c5bb;
    transform: scale3d(1.2, 1.2, 1.2);
    transition: all 0.2s ease-in-out;
  }

  .slide {
    position: absolute;
    height: 2px;
    width: 2rem;
    bottom: -2px;
    transition: all 0.3s ease-in-out;
  }

  .left {
    left: 10%;
    transition: all 0.3s ease-in-out;
  }

  .right {
    left: 90%;
    transition: all 0.3s ease-in-out;
    transform: translateX(-100%);
  }

  .center {
    left: 50%;
    transform: translateX(-50%);
    transition: all 0.3s ease-in-out;
  }
}

.category {
  transition: all 0.2s ease-in-out;
}

.active-category {
  color: #39c5bb;
  //background-color: rgba(57, 197, 187, 0.5);
  transition: all 0.2s ease-in-out;
  transform: scale3d(1.2, 1.2, 1.2);
}
</style>
